//
//  MyYhqViewController.m
//  何五路
//
//  Created by _ADY on 15/8/17.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "MyYhqViewController.h"

@interface MyYhqViewController ()

@end

#define Yhqhight  155/2
#define geHight 50
@implementation MyYhqViewController
@synthesize YhqArray;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    self.view.backgroundColor = bgColor;
    
    
    ccsInt = 0;
    YhqArray = [[NSMutableArray alloc] init];
    NSArray *aAarry = [NSArray arrayWithObjects:@"待领取",@"未使用",@"已过期",@"已使用", nil];
    NSMutableArray* set = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray* set1 = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i = 0;i < 4; i ++)
    {
        NSMutableDictionary *aDadic = [NSMutableDictionary dictionaryWithCapacity:10];
        [aDadic setObject:@"1" forKey:@"pageForNumber"];
        [YhqArray insertObject:aDadic atIndex:i];
        
        [set addObject:[aAarry objectAtIndex:i]];
        [set1 addObject:@""];
        
    }
    NSArray *array = set;
    NSArray *array1 = set1;
    mSidebar = [[MySidebar alloc] initWithFrame:CGRectMake(0, 64, screenMySize.size.width, geHight)];
    mSidebar.delegate = self;
    mSidebar.selectedIndex = ccsInt;
    [mSidebar setTitle:array setImage:array1  setSeclet:array1 setBOOL:YES];
    [self.view addSubview:mSidebar];

    [mSidebar sSelectedSegmentIndex:ccsInt];
    
    
    taScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,geHight+64, self.view.bounds.size.width, self.view.bounds.size.height - geHight-64)];
    taScrollView.backgroundColor = [UIColor whiteColor];
    [taScrollView setDelegate:self];
    [taScrollView setPagingEnabled:YES];
    [taScrollView setShowsHorizontalScrollIndicator:NO];
    [self.view addSubview:taScrollView];
    
    for (int i = 0; i < 4; i ++)
    {
        UITableView *mTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width*i,0, self.view.bounds.size.width, self.view.bounds.size.height-geHight-64) ];
        mTableView.delegate = self;
        mTableView.dataSource = self;
        mTableView.tag = 100+i;
        mTableView.backgroundColor = bgColor;
        [taScrollView addSubview:mTableView];
        
        UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
        [mTableView setTableFooterView:v];
        
        __weak __typeof(self) weakSelf = self;
        
        mTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf loadNewData];
        }];
        mTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        if (i == 0) {
            [mTableView.header beginRefreshing];
        }
    }
    [taScrollView setContentSize:CGSizeMake(self.view.bounds.size.width*4,self.view.bounds.size.height-geHight-64)];
    

    
}

- (void)MySidebar:(int)aType
{
    ccsInt = aType;
    
    [taScrollView scrollRectToVisible:CGRectMake(self.view.bounds.size.width*ccsInt,geHight+64, self.view.bounds.size.width, self.view.bounds.size.height - geHight-64) animated:YES];
    if (![[[YhqArray objectAtIndex:ccsInt] allKeys] containsObject:@"Items"]) {
        UITableView *mTableView = (UITableView*)[self.view viewWithTag:ccsInt+100];
        [mTableView.header beginRefreshing];
    }
    
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    if ([scrollView isKindOfClass:[UITableView class]]) {
        return;
    }
    
    int page =scrollView.bounds.origin.x/self.view.bounds.size.width;
    ccsInt = page;
    [mSidebar sSelectedSegmentIndex:page];
    if (![[[YhqArray objectAtIndex:ccsInt] allKeys] containsObject:@"Items"]) {
        UITableView *mTableView = (UITableView*)[self.view viewWithTag:ccsInt+100];
        [mTableView.header beginRefreshing];
    }
}

- (void)loadNewData
{
    [[YhqArray objectAtIndex:ccsInt] setObject:@"1" forKey:@"pageForNumber"];
    pageForNumber = 1;
    [self upDateTableView];
}
- (void)loadMoreData
{
    NSString *PriceStr = [NSString stringWithFormat:@"%d",[[[YhqArray objectAtIndex:ccsInt] objectForKey:@"pageForNumber"] intValue]+1];
    [[YhqArray objectAtIndex:ccsInt] setObject:PriceStr forKey:@"pageForNumber"];
    
    pageForNumber = [PriceStr intValue];
    [self upDateTableView];
}

-(void)upDateTableView
{
    UITableView *mTableView = (UITableView*)[self.view viewWithTag:ccsInt+100];
    if ((pageForNumber-1)*itemLabel <= [[YhqArray objectAtIndex:ccsInt] count]||pageForNumber ==1)
    {
        NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
        [postDic setObject:[NSNumber numberWithInt:pageForNumber] forKey:@"pageNumber"];
        [postDic setObject:[NSNumber numberWithInt:itemLabel] forKey:@"pageSize"];
        if (ccsInt == 1)
            [postDic setObject:@"0" forKey:@"status"];
        if (ccsInt == 2)
            [postDic setObject:@"2" forKey:@"status"];
        if (ccsInt == 3)
            [postDic setObject:@"1" forKey:@"status"];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
           NSDictionary *ret = nil;
            if (ccsInt == 0) {
                ret = [SendService ReceiveCoupons:postDic];
            }
            else
                ret = [SendService MyCoupon:postDic];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSLog(@"ret %@",ret);
                if (![[NSString stringWithFormat:@"%@",[ret objectForKey:@"Entity"]] isEqualToString:@"<null>"] )
                {
                    if (pageForNumber == 1)
                    {
                        [[YhqArray objectAtIndex:ccsInt] removeAllObjects];
                        
                        NSMutableDictionary *aDadic = [NSMutableDictionary dictionaryWithCapacity:10];
                        [aDadic setObject:@"1" forKey:@"pageForNumber"];
                        [YhqArray insertObject:aDadic atIndex:ccsInt];
                        
                    }
                    NSMutableArray *dicArr = [[NSMutableArray alloc] init];
                    if (ccsInt == 0)
                    {
                        for (NSDictionary *dic in [[ret objectForKey:@"Entity"] objectForKey:@"RuleItem"]) {
                            [dicArr addObject:dic];
                        }
                    }
                    else
                    {
                        for (NSDictionary *dic in [[ret objectForKey:@"Entity"] objectForKey:@"Items"]) {
                            [dicArr addObject:dic];
                        }
                    }
                    [[YhqArray objectAtIndex:ccsInt] setObject:dicArr forKey:@"Items"];
                }
                if (pageForNumber ==1)
                    [mTableView.header endRefreshing];
                else
                    [mTableView.footer endRefreshing];
                [mTableView reloadData];
                
            });
        });
        
    }
    else
    {
        [mTableView.footer noticeNoMoreData];
        [mTableView reloadData];
    }
    
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [[[YhqArray objectAtIndex:ccsInt] objectForKey:@"Items"] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return Yhqhight+30;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyWishList";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        aTableView.showsVerticalScrollIndicator = NO;
    }
    cell.backgroundColor = [UIColor whiteColor];
    
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }

    NSDictionary *aDic = [[[YhqArray objectAtIndex:ccsInt] objectForKey:@"Items"] objectAtIndex:indexPath.row];
    if (ccsInt != 0)
        [cell.contentView addSubview:[self setFrame:CGRectMake(10, 5, 180, 20) setTitle:[NSString stringWithFormat:@"券编号:%@",[aDic objectForKey:@"CouponCode"]] setFont:labelSize-3 setColor:[UIColor blackColor]]];
    
    UIImageView *bg1ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10,25, 180,Yhqhight)];
    [bg1ImageView setImage:[UIImage imageNamed:@"image_couponaback"]];
    [cell.contentView addSubview:bg1ImageView];
    if (ccsInt != 1)
        [bg1ImageView setImage:[UIImage imageNamed:@"coupon_h"]];

    
    NSString *pricString = [NSString stringWithFormat:@"%@",[aDic objectForKey:@"CouponPrice"]];
    NSMutableAttributedString *str= [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"减¥%@满¥%@可用",pricString,[aDic objectForKey:@"UseMinPrice"]]];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 25, 170, 30)];
    titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-3];
    titleLabel.textColor = [UIColor whiteColor];
    
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor]  range:NSMakeRange(2,pricString.length)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:labelSize+2] range:NSMakeRange(2,pricString.length)];
    titleLabel.attributedText = str;
    [cell.contentView addSubview:titleLabel];
    
    NSString *useTypeStr = nil;
    if ([[NSString stringWithFormat:@"%@",[aDic objectForKey:@"UseType"]] isEqualToString:@"1"]) {
        useTypeStr = @"使用条件:满减";
    }
    else
        useTypeStr = @"使用条件:每满减";
    [cell.contentView addSubview:[self setFrame:CGRectMake(20, 55, 170, 10) setTitle:useTypeStr setFont:labelSize-3 setColor:[UIColor whiteColor]]];
    
    NSString * StartTime = [aDic objectForKey:@"StartDate"];
    NSString * endTime = [aDic objectForKey:@"EndDate"];
    StartTime =  [StartTime stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    StartTime =  [StartTime stringByReplacingOccurrencesOfString:@"00:00:00" withString:@""];
    StartTime =  [StartTime stringByReplacingOccurrencesOfString:@"+08:00" withString:@" "];
    endTime =  [endTime stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    endTime =  [endTime stringByReplacingOccurrencesOfString:@"00:00:00" withString:@""];
    endTime =  [endTime stringByReplacingOccurrencesOfString:@"+08:00" withString:@" "];
    
    [cell.contentView addSubview:[self setFrame:CGRectMake(20, 70, 170, 30) setTitle:[NSString stringWithFormat:@"有效时间:%@－%@",StartTime,endTime] setFont:labelSize-3 setColor:[UIColor whiteColor]]];
    
    NSString *aStr= nil;
    if (ccsInt != 0) {
        aStr = [NSString stringWithFormat:@"-全品类(特例商品除外)\n-可在 %@ 使用",[aDic objectForKey:@"ShopName"]];
    }
    else
        aStr=[NSString stringWithFormat:@"-全品类(特例商品除外)\n-可在 %@ 使用",[aDic objectForKey:@"VendorName"]];
    [cell.contentView addSubview:[self setFrame:CGRectMake(200, 25, 100, 60) setTitle:aStr setFont:labelSize-3 setColor:[UIColor blackColor]]];

    NSString *CouponStr = nil;
    if ([[NSString stringWithFormat:@"%@",[aDic objectForKey:@"CouponLevel"]] isEqualToString:@"1"]) {
        CouponStr = @"平台优惠券";
    }
    else if ([[NSString stringWithFormat:@"%@",[aDic objectForKey:@"CouponLevel"]] isEqualToString:@"2"])
        CouponStr = @"店铺优惠券";
    else
        CouponStr = @"单品优惠券";
    [cell.contentView addSubview:[self setFrame:CGRectMake(200, Yhqhight+10, 100, 20) setTitle:[NSString stringWithFormat:@"来源:%@",CouponStr] setFont:labelSize-3 setColor:[UIColor blackColor]]];

    if (ccsInt == 0)
    {
        if ([[NSString stringWithFormat:@"%@",[aDic objectForKey:@"ReceiveNum"]] intValue] > 0)
        {
            UIImageView *bg2ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(115,25, 70,70)];
            [bg2ImageView setImage:[UIImage imageNamed:@"yhqylq"]];
            [cell.contentView addSubview:bg2ImageView];
            [bg1ImageView setImage:[UIImage imageNamed:@"image_couponaback"]];
        }
        else if ([[NSString stringWithFormat:@"%@",[aDic objectForKey:@"SendCount"]] intValue] == 0)
        {
            UIImageView *bg2ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(115,25, 70,70)];
            [bg2ImageView setImage:[UIImage imageNamed:@"yhqyqg"]];
            [cell.contentView addSubview:bg2ImageView];
        }
        else
            [bg1ImageView setImage:[UIImage imageNamed:@"image_couponaback"]];
    }
    
    // Configure the cell...
    return cell;
}

-(UILabel*)setFrame:(CGRect)frame setTitle:(NSString*)title setFont:(int)font setColor:(UIColor*)myColor
{
    title = [title stringByReplacingOccurrencesOfString:@"<null>" withString:@""];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];
    if (title != nil)
        titleLabel.text = [NSString stringWithFormat:@"%@",title];
    titleLabel.textAlignment = 0;
    titleLabel.numberOfLines = 0;
    titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:font];
    titleLabel.textColor = myColor;
    return titleLabel;
}


#pragma mark 点击响应事件
- (void)tableView:(UITableView *)table1View didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (ccsInt == 0)
    {
        NSDictionary *aDic = [[[YhqArray objectAtIndex:ccsInt] objectForKey:@"Items"] objectAtIndex:indexPath.row];
        if ([[NSString stringWithFormat:@"%@",[aDic objectForKey:@"ReceiveNum"]] intValue] > 0)
        {

        }
        else if ([[NSString stringWithFormat:@"%@",[aDic objectForKey:@"SendCount"]] intValue] == 0)
        {

        }
        else
        {
            NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
            [postDic setObject:[aDic objectForKey:@"Id"] forKey:@"ruleId"];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
                NSDictionary *ret = [SendService ImmediatelyReceive:postDic];
                dispatch_async(dispatch_get_main_queue(), ^{

                    if (![[NSString stringWithFormat:@"%@",[ret objectForKey:@"Message"]] isEqualToString:@"<null>"] )
                    {
                        [SendService alerViewMessage:[ret objectForKey:@"Message"]];
                    }
                    
                });
            });

            
        }
    }
    [table1View deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
